/*
 * Copyright (c) 2024 Shenzhen Kaihong Digital Industry Development Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
 
#include <stdio.h>
#include <stdbool.h>
#include <assert.h>
#include <string.h>

#include "log.h"
#include "bts_le_gap.h"
#include "ohos_bt_gap.h"

static bool bleEnableFlag = false;

bool EnableBle(void)
{
    errcode_t ret = ERRCODE_BT_FAIL;

    HILOG_DEBUG(0, "[bluetooth] EnableBle\n");
    ret = enable_ble();
    if (ERRCODE_BT_SUCCESS == ret) {
        bleEnableFlag = true;
    }
    unsigned char efuse_left_count = 0;
    uint8_t mac[BD_ADDR_LEN] = {0};
    if (efuse_read_mac(mac, BD_ADDR_LEN, &efuse_left_count) == ERRCODE_SUCC) {
        HILOG_DEBUG(0, "[bluetooth] efuse_read_mac failed\n");
        mac[BD_ADDR_LEN -1] = mac[BD_ADDR_LEN -1] + 1;
        bd_addr_t ble_speed_addr = {.type = 0};
        memcpy_s(ble_speed_addr.addr, BD_ADDR_LEN, mac, BD_ADDR_LEN);
        gap_ble_set_local_addr(&ble_speed_addr);
    } else {
        HILOG_DEBUG(0, "[bluetooth] efuse_read_mac failed\n");
    }

    return (ERRCODE_BT_SUCCESS == ret) ? true : false;
}

bool DisableBle(void)
{
    errcode_t ret = ERRCODE_BT_FAIL;

    HILOG_DEBUG(0, "[bluetooth] DisableBle\n");

    ret = disable_ble();
    if (ERRCODE_BT_SUCCESS == ret) {
        bleEnableFlag = false;
    }
    return (ERRCODE_BT_SUCCESS == ret) ? true : false;
}

bool IsBleEnabled(void)
{
    return bleEnableFlag;
}

bool GetLocalAddr(unsigned char *mac, unsigned int len)
{
    HILOG_DEBUG(0, "[bluetooth] GetLocalAddr\n");
    errcode_t ret = ERRCODE_BT_FAIL;
    bd_addr_t bleAddr;
    ret = gap_ble_get_local_addr(&bleAddr);
    if(ERRCODE_BT_SUCCESS == ret){
        memcpy_s(mac, len, bleAddr.addr, BD_ADDR_LEN);
        return true;
    }else{
        return false;
    }
}
